<?php
Yii::import('application.vendors.*');
require_once('ChartDirector/lib/phpchartdir.php');
require_once('ChartDirector/lib/financefunction.php');
class AjaxController extends Controller {

    public function actionIndex() {
        $this->render('index');
    }

    /////////////////////////////////////////////////////////////////////
    // Uncomment the following methods and override them if needed
    /*
      public function filters()
      {
      // return the filter configuration for this controller, e.g.:
      return array(
      'inlineFilterName',
      array(
      'class'=>'path.to.FilterClass',
      'propertyName'=>'propertyValue',
      ),
      );
      }

      public function actions()
      {
      // return external action classes, e.g.:
      return array(
      'action1'=>'path.to.ActionClass',
      'action2'=>array(
      'class'=>'path.to.AnotherActionClass',
      'propertyName'=>'propertyValue',
      ),
      );
      }
     */
    public function actionPreviewImportFromWeb() {

        if (Yii::app()->request->isAjaxRequest)
        {
            /// Lay thong tin tu form
            define("XPATH", '//html/body/table[@id="table_body"]/tbody/tr/td/table/tr/td/form/table/tr/td/table/tr/td/table[@class="ctq"]/tr[position()>2 and position()!=last()]', true);
            $house = Yii::app()->request->getPost('house');
            $fromMa = Yii::app()->request->getPost('from');
            $toMa = Yii::app()->request->getPost('to');
            $maChungKhoan = Yii::app()->request->getPost('stock_id');
            $bitCheck = 1; // Kiem tra xem co tiep tuc query page tiep theo hay k
            $page = 1; // page dau tien la 1
            while ($bitCheck == 1) {
                // Lay url
                //$url ='http://priceboard.fpts.com.vn/user/stock/lich-su/?a=2&c=1&s=AAM&t=0&d=27/07/2011&b=02/06/2011&e=04/06/2011&p=1';
                $url = 'http://priceboard.fpts.com.vn/user/stock/lich-su/?a=2&c=' . $house . '&s=' . $maChungKhoan . '&t=0&d=27/07/2011&b=' . $fromMa . '&e=' . $toMa . '&p=' . $page;
                // ma hoa url, thay the cac ki tu dac biet
                $url = Stock::model()->replaceString($url);
                $xpath = Stock::model()->replaceString(XPATH);

                // Lay xml tu server yahoo (Minh se khong truy cap truc tiep tu server fpt ma thong qua yahoo)
                $file = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22' . $url . '%22%20and%0A%20%20%20%20%20%20xpath%3D\'' . $xpath . '\'&diagnostics=true';
                $fromMa_t = str_replace("/", "", $fromMa);
                $toMa_t = str_replace("/", "", $toMa);

                // tao file.
                $newfile = 'upload/importfromweb/' . $house . '-' . $maChungKhoan . '-' . $page . '-' . $fromMa_t . $toMa_t . '.txt';
                if (!copy($file, $newfile))
                {
                    echo "failed to copy $file...\n";
                }
                $buffer = "";
                $myFile = $newfile;

                // mo file
                $handle = @fopen($myFile, 'r');
                if ($handle)
                {
                    echo "<b>Page " . $page . "</b><br><br>";
                    echo "<div id=\"stock-grid\" class=\"grid-view\" >

                    <table class=\"items\">
                        <thead>
                            <tr style=\"color: rgba(0, 0, 0, .4);  font-weight: bold;  text-decoration: none; font-size: 10pt;\">
                                <th id=\"stock-grid_c0\">Ngày</th><th id=\"stock-grid_c1\">M?</th><th id=\"stock-grid_c2\">Tham Chi?u</th><th id=\"stock-grid_c3\">Tr?n</th><th id=\"stock-grid_c4\">Sàn</th><th id=\"stock-grid_c5\">M? c?a</th><th id=\"stock-grid_c6\">Đóng c?a</th><th id=\"stock-grid_c7\">Cao nh?t</th><th id=\"stock-grid_c8\">Th?p nh?t</th><th id=\"stock-grid_c9\">TB</th><th id=\"stock-grid_c10\">KL kh?p l?nh</th><th id=\"stock-grid_c11\">KL tho? thu?n</th><th id=\"stock-grid_c12\">GT kh?p l?nh</th><th id=\"stock-grid_c13\">GT tho? thu?n</th>
                            </tr>
                        </thead>
                    <tbody>";

                    // bien nay de kiem tra xem co tiep tuc doc page tiep theo hay k. Neu count <200 -> stop k doc nua.
                    $CountPageToCheck = 0;
                    $CountRow = 0;
                    while (!feof($handle)) {
                        $buffer = $buffer . fgetc($handle);
                        //echo $buffer."<br>";
                        // doc tung doan trong file, phan cach boi </tr>
                        $pos = strripos($buffer, '/tr>');

                        if ((strlen($buffer) - $pos) <= 4 && strlen($buffer) > 10)
                        {
                            //	echo $buffer."<br><br><br>";
                            // doc buffer
                            $html = str_get_html($buffer);
                            //echo $html;
                            if ($CountRow % 2 == 0)
                                echo "<tr class=\"odd\">"; else
                                echo "<tr class=\"even\">";
                            $count = 1;

                            // tim the <td>
                            foreach ($html->find('td') as $p) {
                                // loai bo 1 so dong du. de mapping vao database cua minh.
                                if ($count != 11 && $count != 12 && $count != 15 && $count != 18)
                                {
                                    echo"<td>";
                                    echo $p->innertext;
                                    echo "</td>";
                                }
                                $count++;
                            }
                            $CountRow++;
                            echo "</tr>";

                            // reset buffer va tang bien count
                            $buffer = "";
                            $CountPageToCheck++;
                        }
                    }

                    // kiem tra neu count < 200 thi k tiep tuc
                    if ($CountPageToCheck < 200)
                    {
                        $bitCheck = 0;
                    }

                    echo "</tbody></table></div>";
                    fclose($handle);
                }
                $page++;
            }
        }
    }
    

    public function actionStartImportFromWeb() {
        if (Yii::app()->request->isAjaxRequest)
        {
            // lay thong tin tu form
            define("XPATH", '//html/body/table[@id="table_body"]/tbody/tr/td/table/tr/td/form/table/tr/td/table/tr/td/table[@class="ctq"]/tr[position()>2 and position()!=last()]', true);
            $house = Yii::app()->request->getPost('house');
            $fromMa = Yii::app()->request->getPost('from');
            $toMa = Yii::app()->request->getPost('to');
            $maChungKhoan = Yii::app()->request->getPost('stock_id');
            $sanChungKhoan = Yii::app()->request->getPost('house');
            $bitCheck = 1;
            $page = 1;
            while ($bitCheck == 1) {
                // file nguon
                $url = 'http://priceboard.fpts.com.vn/user/stock/lich-su/?a=2&c=' . $house . '&s=' . $maChungKhoan . '&t=0&d=27/07/2011&b=' . $fromMa . '&e=' . $toMa . '&p=' . $page;
                //$url ='http://priceboard.fpts.com.vn/user/stock/lich-su/?a=2&c=1&s=AAM&t=0&d=27/07/2011&b=02/06/2011&e=04/06/2011&p=1';
                $url = Stock::model()->replaceString($url);
                $xpath = Stock::model()->replaceString(XPATH);
                $file = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22' . $url . '%22%20and%0A%20%20%20%20%20%20xpath%3D\'' . $xpath . '\'&diagnostics=true';
                $fromMa_t = str_replace("/", "", $fromMa);
                $toMa_t = str_replace("/", "", $toMa);
                // file dich
                $newfile = 'upload/importfromweb/' . $house . '-' . $maChungKhoan . '-' . $page . '-' . $fromMa_t . $toMa_t . '.txt';
                if (!copy($file, $newfile))
                {
                    echo "failed to copy $file...\n";
                }
                $buffer = "";
                $myFile = $newfile;
                $handle = @fopen($myFile, 'r');
                if ($handle)
                {
                    $CountPageToCheck = 0;
                    while (!feof($handle)) {
                        // doc buffer
                        $buffer = $buffer . fgetc($handle);
                        $pos = strripos($buffer, '/tr>');

                        if ((strlen($buffer) - $pos) <= 4 && strlen($buffer) > 10)
                        {
                            $html = str_get_html($buffer);
                            $count = 1;
                            // tao model
                            $model = new Stock();
                            $timestamp = "";
                            // tim the <td>
                            foreach ($html->find('td') as $td) {

                                if ($count != 11 && $count != 12 && $count != 15 && $count != 18)
                                {

                                    // gan noi dung vao model
                                    switch ($count) {
                                        case 1:
                                            // xu ly timestamp
                                            $model->timestamp = Stock::model()->remoreString($td->innertext);
                                            $timestamp = Company::model()->fixtags($model->timestamp);
                                            //$model->timestamp = Company::model()->fixtags($model->timestamp);
                                            $pieces = explode("/", $timestamp);
                                            $model->timestamp = $pieces[2] . "-" . $pieces[1] . "-" . $pieces[0] . " 00:00:00";

                                            break;
                                        case 2:
                                            // su ly ticket , neu chua co thi them moi.
                                            $tempTicketID = Stock::model()->remoreString($td->innertext);
                                            $tempTicketID = Company::model()->fixtags($tempTicketID);
                                            $StockObj = Company::model()->findByAttributes(array('ticket' => $tempTicketID));
                                            if (is_null($StockObj))
                                            {
                                                Company::model()->saveCompany($tempTicketID);
                                                $TempStockObj = Company::model()->findByAttributes(array('ticket' => $tempTicketID));
                                                $model->companyID = $TempStockObj->id;
                                            } else
                                                $model->companyID = $StockObj->id;
                                            break;
                                        case 3:
                                            $model->ref = floatval(Stock::model()->remoreString($td->innertext));
                                            break;
                                        case 4:
                                            $model->ceiling = floatval(Stock::model()->remoreString($td->innertext));
                                            break;
                                        case 5:
                                            $model->floor = floatval(Stock::model()->remoreString($td->innertext));
                                            break;
                                        case 6:
                                            $model->open = floatval(Stock::model()->remoreString($td->innertext));
                                            break;
                                        case 7:
                                            $model->close = floatval(Stock::model()->remoreString($td->innertext));
                                            break;
                                        case 8:
                                            $model->high = floatval(Stock::model()->remoreString($td->innertext));
                                            break;
                                        case 9:
                                            $model->low = floatval(Stock::model()->remoreString($td->innertext));
                                            break;
                                        case 10:
                                            $model->avg = floatval(Stock::model()->remoreString($td->innertext));
                                            break;
                                        case 13:
                                            $model->volumeKhopLenh = floatval(Stock::model()->remoreString($td->innertext));
                                            break;
                                        case 14:
                                            $model->volumeAgreement = floatval(Stock::model()->remoreString($td->innertext));
                                            break;
                                        case 16:
                                            $model->valueKhopLenh = floatval(Stock::model()->remoreString($td->innertext));
                                            break;
                                        case 17:
                                            $model->valueAgreement = floatval(Stock::model()->remoreString($td->innertext));
                                            break;
                                    }
                                }
                                $count++;
                            }
                            $duplication = Stock::model()->findByAttributes(array('timestamp' => $model->timestamp,'companyID' => $model->companyID));
                            if(is_null($duplication)) Stock::model()->saveStock($model->timestamp, $model->companyID, $sanChungKhoan, $model->ref, $model->ceiling, $model->floor, $model->open, $model->close, $model->high, $model->low, $model->avg, $model->volumeKhopLenh, $model->volumeAgreement, $model->valueKhopLenh, $model->valueAgreement);


                            $buffer = "";
                            $CountPageToCheck++;
                        }
                    }
                    if ($CountPageToCheck < 200)
                        $bitCheck = 0;
                    fclose($handle);
                }
                $page++;
            }
        }
    }

    public function actionGetStockID() {
        if (isset($_POST['id']))
        {
            // file chua ma chung khoan tu server fpt
            $data = file_get_contents('http://priceboard.fpts.com.vn/user/stock/_/_co.js');
            $pieces = explode(";", $data);
            $data1 = explode(",", $pieces[0]);
            $data2 = explode(",", $pieces[1]);
            $data = file_get_contents('http://priceboard.fpts.com.vn/user/stock/_/_upcom.js');
            $pieces = explode(";", $data);
            $data3 = explode(",", $pieces[0]);
            if ($_POST['id'] == '1')
            {
                echo '<option value="">T?t c?</option>';
                $count = 1;
                foreach ($data1 as $temp) {
                    $temp = str_replace("\"", "", $temp);
                    $temp = str_replace(")", "", $temp);
                    if ($count != 1)
                        echo '<option value="' . $temp . '">' . $temp . '</option>'; else
                    {
                        $temp_data = explode("(", $temp);
                        echo '<option value="' . $temp_data[1] . '">' . $temp_data[1] . '</option>';
                    }
                    $count++;
                }
            }
            else if ($_POST['id'] == '2')
            {
                echo '<option value="">T?t c?</option>';
                $count = 1;
                foreach ($data2 as $temp) {
                    $temp = str_replace("\"", "", $temp);
                    $temp = str_replace(")", "", $temp);
                    if ($count != 1)
                        echo '<option value="' . $temp . '">' . $temp . '</option>'; else
                    {
                        $temp_data = explode("(", $temp);
                        echo '<option value="' . $temp_data[1] . '">' . $temp_data[1] . '</option>';
                    }
                    $count++;
                }
            }
            else if ($_POST['id'] == '4')
            {
                echo '<option value="">T?t c?</option>';
                $count = 1;
                foreach ($data3 as $temp) {
                    $temp = str_replace("\"", "", $temp);
                    $temp = str_replace(")", "", $temp);
                    if ($count != 1)
                        echo '<option value="' . $temp . '">' . $temp . '</option>'; else
                    {
                        $temp_data = explode("(", $temp);
                        echo '<option value="' . $temp_data[1] . '">' . $temp_data[1] . '</option>';
                    }
                    $count++;
                }
            }
        }
    }
    public function matrixRotation($A)
		{
				$temp = array();
				$j=0;
				for($i=count($A)-1;$i>=0;$i--)
				{
						$temp[$j]=$A[$i];
						$j++;
				}
				return $temp;
		}
		
		public function findDay($numberDay)
		{
				$today = date("Y-m-d 00:00:00");
				$pieces = explode(" ", $today);				
				$dayValue = explode("-", $pieces[0]);
				$day = $dayValue[2];
				$month = $dayValue[1];
				$year = $dayValue[0];
				while($numberDay>0)
				{
					if($numberDay>365)
					{
							$numberDay = $numberDay - 365;
							$year = $year - 1;
					} else if($numberDay>30)
					{
							$numberDay = $numberDay - 30;
							$month = $month - 1;
							if($month==0) {
									$year = $year-1;
									$month = 12;
							}
					} else {
							$numberDay = 0;
							$day = $day - $numberDay;
							if($day<=0) {
								$month = $month -1;
								if($month==0)
								{
									$month = 12;
									$year = $year - 1;
								}
								
								$day = 30 + $day;
							}
					}
				}
				
				return "$year-$month-$day 00:00:00";
		}
		
    public function actionFormulaCalGetData() {
            $numPort = 300;
            $testMode = 0; 
            session_start();
            $filename = session_id();
            $countAsset = Yii::app()->request->getPost('house');
            $NumPorts = 200;
            $BorrowRate = Yii::app()->request->getPost('BorrowRate');
            $InvestmentHorizon = Yii::app()->request->getPost('depth')*7;
            $ReturnStep = Yii::app()->request->getPost('step');
            //$InvestmentHorizon = 30;
            //$ReturnStep = 1;
            $connection=Yii::app()->db;
            $StockValue = array(); /// Array Gia tri Close Price
            $ReturnValue = array(); /// Array Return value
            $TimeValue0 = array(); // Array Time  = 0
            $TimeValue = array(); /// Array Time != 0
							$TimeValue11 = array(); /// Array Time != 0
            $StockIDValue = array(); /// Array Stock ID
            $MeanArray = array(); /// Array Mean
            $StdArray = array(); /// Array Std
            $CorrelationArray = array();
            for($i=1;$i<=$countAsset;$i++)
            {
                $temp = Yii::app()->request->getPost('stock_id'.$i);
                $sql = "SELECT id FROM company WHERE ticket = '".$temp."'";
                $command=$connection->createCommand($sql);
                $dataReader=$command->queryAll();
                foreach($dataReader as $row) {
                    array_push($StockIDValue,$row['id']);
                }
            }
            if($testMode==1) { echo "<b>Stock ID: </b>";
            var_dump($StockIDValue); 
            echo "<br><br>"; }
            /////////////////// begin - Lay array thoi gian hop le
            $sql = "SELECT DISTINCT timestamp FROM stock WHERE ";// company.ticket = '".$temp."' AND company.id = stock.companyID ORDER BY timestamp DESC LIMIT ".$InvestmentHorizon;
            $count = 0;
            foreach ($StockIDValue as $tempStock)
            {
                if($count==0) $sql .= "(companyID = ".$tempStock." "; else $sql .= " OR companyID = ".$tempStock."";
                $count++;
            }
            $sql .= ") AND close = 0 ORDER BY timestamp DESC LIMIT ".$InvestmentHorizon;
            //echo $sql."<br>";
            $command=$connection->createCommand($sql);
            $dataReader=$command->queryAll();
            
            foreach($dataReader as $row) {
                array_push($TimeValue0,$row['timestamp']);                           
            }
            
            
           

            //////////////////////////////////
            $sql = "SELECT DISTINCT timestamp FROM stock WHERE ";// company.ticket = '".$temp."' AND company.id = stock.companyID ORDER BY timestamp DESC LIMIT ".$InvestmentHorizon;
            $count = 0;
            foreach ($StockIDValue as $tempStock)
            {
                if($count==0) $sql .= "(companyID = ".$tempStock." "; else $sql .= " OR companyID = ".$tempStock."";
                $count++;
            }
            $sql .= ") ";// close = 0 ORDER BY timestamp DESC LIMIT ".$InvestmentHorizon;
            foreach ($TimeValue0 as $tempStock)
            {
               $sql .= " AND timestamp != '".$tempStock."'";
            }
            $sql .= " ORDER BY timestamp DESC LIMIT ".$InvestmentHorizon;
							
							
							
            $command=$connection->createCommand($sql);
            $dataReader=$command->queryAll();
            $nextDay = "";
            $countDay = 0;
            foreach($dataReader as $row) {
                if(($countDay%$ReturnStep)==0) array_push($TimeValue,$row['timestamp']);
                $countDay++;
            }
          
            if($testMode==1) { echo "<b>Timestamp: </b>";
            var_dump($TimeValue);
            echo "<br><br>"; }
            //////////// end - lay array thoi gian hop le
            //////////// begin - doc du lieu stock
            $bitStockA = 1;
            for($i=1;$i<=count($StockIDValue);$i++)
            {
                $StockArrayTemp = array();
                $sql = ""; //timestamp = '".$temp."' AND company.id = stock.companyID ORDER BY timestamp DESC LIMIT ".$InvestmentHorizon;
                $count = 0;
               /* foreach($TimeValue as $timeTemp)
                {
                    if($count==0) $sql .= "(timestamp = '".$timeTemp."'"; else $sql .= " OR timestamp = '".$timeTemp."'";
                    $count++;
                }*/
									$dayBegin = $this->findDay($InvestmentHorizon);
									//echo $dayBegin;
                $sql .= "companyID = ".$StockIDValue[$i-1]." AND timestamp >= '$dayBegin' ORDER BY timestamp ASC";
                
									$db = Stock::model()->findAll($sql);
									$count = count($db) - 1;
									//echo $db[0]->timestamp;
									//echo $db[139]->timestamp;
									$aaf = adjustPrice($db);
									//print_r($aaf);
								//	echo "<br>";
									$h = 0;
									for($j = 0; $j <= $count; $j++) {
										//if($db[$j]->close!='0') {
										for($k=0;$k<count($TimeValue);$k++)
										{
												if($TimeValue[$k]==$db[$j]->timestamp) { 
														$StockArrayTemp[$h]=$aaf[$j]*$db[$j]->close;
														$h++;
														$k=count($TimeValue);
														//$tempTime = $TimeValue[$k];
													  if($bitStockA == 1) array_push($TimeValue11,$db[$j]->timestamp);
												//array_push($TimeValue1,$TimeValue[$k]);
												} 
				   // if($count==0) $sql .= "(timestamp = '".$timeTemp."'"; else $sql .= " OR timestamp = '".$timeTemp."'";
                    //$count++;
										}
											
										//	$VNINDEX_Data[] = round($VNINDEX[$i]->close,3);											
									//	}
									}
									$bitStockA = 0;
								///	print_r($StockArrayTemp);
									array_push($StockValue,$StockArrayTemp);
                unset($StockArrayTemp);
				
				//echo "test";
									//echo $sql."<br>";
                /*$command=$connection->createCommand($sql);
                $dataReader=$command->queryAll();
                foreach($dataReader as $row) {
                    array_push($StockArrayTemp,$row['close']);
                }*/
                
            }
						  $TimeValue11=$this->matrixRotation($TimeValue11);
						  for($i=0;$i<$countAsset;$i++)
						  {
									$StockValue[$i]=$this->matrixRotation($StockValue[$i]);
						  }
            if($testMode==1) { echo "<b>Close Price: </b>";
            var_dump($StockValue);
            echo "<br><br>"; }
							 if($testMode==1) { 
								for($i=0;$i<count($StockValue[0]);$i++)
								{
								  echo $TimeValue11[$i];
									echo ",";
									for($j=0;$j<$countAsset;$j++)
									{
										echo $StockValue[$j][$i];
										echo ",";
									}
									echo "<br>";
								}
							 }
            
         
          //////////// end : doc du lieu stock
            ////////// Begin : tinh return array
         for($i=0;$i<count($StockValue);$i++)
            {
                //echo $i;
                $StockArrayTemp = array();
                //echo "<br>";
                for($j=0;$j<count($StockValue[$i])-1;$j++)
                {
                    if($StockValue[$i][$j+1]!=0)
					$temp = $StockValue[$i][$j]/$StockValue[$i][$j+1]; else $temp = $StockValue[$i][$j-1]/$StockValue[$i][$j];
                    //echo $StockValue[$i][$j]." ; ".$StockValue[$i][$j+$ReturnStep]." ; ".$temp."<br>";
                    $Log10Temp = log10($temp)/log10(2.718282);
                    array_push($StockArrayTemp,$Log10Temp);
                }
                array_push($ReturnValue,$StockArrayTemp);
                unset($StockArrayTemp);
            }
            if($testMode==1) { echo "<b>Return Array: </b>";
            var_dump($ReturnValue);
            echo "<br><br>"; }
       
            
            /////////////////// end: tinh return array
            /// begin : tinh mean
            $stepQuare = 252/$ReturnStep;
            
            for($i=0;$i<count($ReturnValue);$i++)
            {
                array_push($MeanArray,array_sum($ReturnValue[$i])*$stepQuare/count($ReturnValue[$i]));
            }
            if($testMode==1) { echo "<b>Mean: </b>";
            var_dump($MeanArray);
            echo "<br><br>"; }

            /// end : tinh mean

            /// begin : tinh standard deviation
            for($i=0;$i<count($ReturnValue);$i++)
            {
                array_push($StdArray,Stock::model()->standard_deviation($ReturnValue[$i],true)*sqrt($stepQuare));
            }
            if($testMode==1) { echo "<b>Standard Deviation : </b>";
            var_dump($StdArray);
            echo "<br><br>"; }

            /// end : tinh standard deviation
            
            /// begin : Tinh Correlation
            for($i = 0;$i<count($ReturnValue);$i++)
            {
                for($j = 0; $j < count($ReturnValue);$j++)
                {
                    array_push($CorrelationArray,round(Stock::model()->Correlation($ReturnValue[$i],$ReturnValue[$j]),4));
                }
            }

            
            if($testMode==1) { echo "<b>Correlation: </b>";
            var_dump($CorrelationArray);
            echo "<br><br>"; } 
            
            
            
            
            
            /////////////////////////////////////////////
            $test = Yii::app()->request->getPost('house');
            echo "
            <div id=\"stock-grid\" class=\"grid-view\">
                <table class=\"items\" style='margin-bottom: 2px;'>
                    <tr>
                    <td>";

            echo "<TABLE border=1 style='margin-bottom: 2px;'>
					  <TR> <TH Valign=\"bottom\">Asset #</TH>
						   <TH Align=\"center\">Stock";                  
               echo "</TH>
						   <TH Align=\"center\">Initial Weight</TH><TH Align=\"center\">Mean</TH><TH Align=\"center\">Std</TH><TH Align=\"center\" colspan=\"".$test."\">Correlation</TH>
					  </TR> ";
               echo "<tr><th></th><th></th><th></th><th></th><th></th>";
               for($i = 1; $i <= $test; $i++) {
                $stockid = Yii::app()->request->getPost('stock_id'.$i);  
                echo "<th>$stockid</th>";
               }
               echo "</tr>"; 
								for ($i = 1; $i <= $test; $i++) {
                    $stockid = Yii::app()->request->getPost('stock_id'.$i);
                    echo "<tr><td>$i</td><td><b>$stockid</b>
                       </td><td><INPUT Name=\"iwt$i\" SIZE=6></td>";
                    echo "<td><INPUT id=\"mean$i\" Name=\"mean$i\" value=\"".$MeanArray[$i-1]."\" SIZE=6";
                    if($MeanArray[$i-1]<0) echo " style=\"background: #ED6409;\" "; else echo " style=\"background: #4d99ea;\" ";
                    echo "><input type='button' value='Change' class='btChangeMean' id='_$i' /></td>";
                    echo "<td><INPUT Name=\"std$i\" value=\"".$StdArray[$i-1]."\" SIZE=6></td>";
                    for($j = 1; $j <= $test; $j++)
                    {
                        if($i==$j) echo "<td>1</td>";
                        if($i>$j) echo "<td><INPUT Name=\"corr$i-$j\" value=\"".$CorrelationArray[($i-1)*$test+($j-1)]."\" SIZE=6></td>"; else "<td></td>";
                    }
                    echo "</tr>";
								}
								echo "</table>";
              
              echo"</td></tr></table></div>";
				
					
    }
    
    public function actionCountForm() {
        if (isset($_POST['id']))
        {
            echo "
            <div id=\"stock-grid\" class=\"grid-view\">
                <table class=\"items\" style='margin-bottom: 2px;'>
                    <tr><td valign=\"top\">
                        <table>";
            //echo "<tr><td><B>NumPorts</B></td><td><INPUT value=\"20\" Name=\"NumPorts\" SIZE=16></td></tr>";
            echo "<tr><td><B>Exp</B></td><td><INPUT value=\"0.55\" Name=\"BorrowRate\" SIZE=3></td></tr>";
            echo "<tr><td><B>Depth</B></td><td><INPUT value=\"30\" Name=\"depth\" SIZE=3></td></tr>";
            echo "<tr><td><B>Step</B></td><td><INPUT value=\"1\" Name=\"step\" SIZE=3></td></tr>";
            echo "
                        </table>
                    </td>
                    <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
                    <td>";

			     echo "<TABLE border=1 style='margin-bottom: 2px;'>
					  <TR> <TH Valign=\"bottom\">Asset #</TH>
						   <TH Align=\"center\">Stock";
           
               echo "</TH>";
					//	   <TH Align=\"center\">Initial Weight</TH><TH Align=\"center\">Mean</TH><TH Align=\"center\">Std</TH><TH Align=\"center\" colspan=\"".$_POST['id']."\">Correlation</TH>
					 echo "</TR> ";					
					for ($i = 1; $i <= $_POST['id']; $i++) {
                    echo "<tr><td>$i</td><td>
                        <select id=\"stock_id$i\" name=\"stock_id$i\" class=\"stock_id$i\">
                        <option value=\"\">All</option>";
                    $CompanyData = Stock::model()->getCompanyOptions();
                     echo $CompanyData;      
                     echo   "</select></td>";
                  
                    echo "</tr>";
								}
								echo "</table>";
              
              echo"</td></tr></table></div>";

						
        }
    }
    
    public function actionCLR() {

        if (Yii::app()->request->isAjaxRequest)
        {
            /// Lay thong tin tu form
            $closeData = array();
            $house = Yii::app()->request->getPost('house');
            $fromMa = Yii::app()->request->getPost('from');
            $toMa = Yii::app()->request->getPost('to');
            $maChungKhoan = Yii::app()->request->getPost('stock_id');
            $ReturnStep = Yii::app()->request->getPost('step');
            $testMode = 0;
            $pieces = explode("/", $fromMa);
            $fromMa = $pieces[2]."-".$pieces[1]."-".$pieces[0]." 00:00:00";
            $pieces = explode("/", $toMa);
            $toMa = $pieces[2]."-".$pieces[1]."-".$pieces[0]." 00:00:00";
            $StockObj = Company::model()->findByAttributes(array('ticket' => $maChungKhoan));
            $query = "companyID = " . $StockObj->id . " and (timestamp BETWEEN '". $fromMa . "' and '".$toMa."') ORDER BY timestamp ASC";
            $db = Stock::model()->findAll($query);
            if($house==1) $StockObj = Company::model()->findByAttributes(array('ticket' => 'VNINDEX')); else if($house==2) $StockObj = Company::model()->findByAttributes(array('ticket' => 'HASTC'));
            $query = "companyID = " . $StockObj->id . " and (timestamp BETWEEN '". $fromMa . "' and '".$toMa."')  ORDER BY timestamp DESC";
            $VNINDEX = Stock::model()->findAll($query);
            
           $count = count($db) - 1;
            $aaf = adjustPrice($db);           
            for($i = 0; $i <= $count; ++$i) {
                if($db[$i]->close!='0'&&$i%$ReturnStep==0) {
                    $closeData[] = round($db[$i]->close * $aaf[$i],3);
                    $VNINDEX_Data[] = round($VNINDEX[$i]->close,3);											
                }
            }
            $temp = array();
            for($i =0; $i<=$count; ++$i)
            {
                if($db[$i]->close!='0'&&$i%$ReturnStep==0)
                array_push($temp,$db[$i]->close);
            }
            
            $dateStamp = array();
            for($i =0; $i<=$count; ++$i)
            {
                if($db[$i]->timestamp!='0'&&$i%$ReturnStep==0)
                array_push($dateStamp,$db[$i]->timestamp);
            }
							$closeData=$this->matrixRotation($closeData);
							$temp=$this->matrixRotation($temp);
							$dateStamp=$this->matrixRotation($dateStamp);
           if($testMode==1) {
                echo "<table><tr><td><h3>Date</h3></td><td><h3>Gia Goc</h3></td><td><h3>Gia Dieu Chinh</h3></td><td><h3>VNINDEX</h3></td></tr><tr><td>";
                var_dump($dateStamp);
                echo "</td><td>";  
                var_dump($temp);
                echo "</td><td>";
                var_dump($closeData);
                echo "</td><td>";
                var_dump($VNINDEX_Data);
                echo "</td></tr></table>";
            }
							if($testMode==1) { echo "<br><br>";
									for($i=0;$i<count($closeData);$i++)
									{
										echo $dateStamp[$i].";".round($closeData[$i],3).";".$VNINDEX_Data[$i];
										echo "<br>";
									}
							}
            $ReturnValueStock = array();
            $ReturnValueVNIndex = array();
             for($i=0;$i<count($closeData)-1;$i++)
            {
                
									if($closeData[$i+1]!=0) $Log10Temp = log(floatval($closeData[$i])/floatval($closeData[$i+1]));
									else $Log10Temp = log(floatval($closeData[$i]+0.01)/floatval($closeData[$i+1]+0.01));
                $Log10TempVN = log(floatval($VNINDEX_Data[$i])/floatval($VNINDEX_Data[$i+1]));
                array_push($ReturnValueStock,$Log10Temp);
                array_push($ReturnValueVNIndex,$Log10TempVN);
            }
							//echo array_sum($ReturnValueStock).count($ReturnValueStock);
            $returnValue = array_sum($ReturnValueStock)/count($ReturnValueStock);
            $SSTot = 0;
            $SSReg = 0;
             for($i =0; $i<count($ReturnValueStock); $i++)
            {
                $SSTot = $SSTot + ($ReturnValueStock[$i] - $returnValue)*($ReturnValueStock[$i] - $returnValue);
            }
            if($testMode==1) { echo "<b>Return Array: </b>";
                echo "<table><tr><td><h3>Stock</h3></td><td><h3>VN-Index</h3></td></tr><tr><td>";
                var_dump($ReturnValueStock);
                echo "</td><td>";
                var_dump($ReturnValueVNIndex);
                echo "</td></tr></table>";
            }
            $averStock = array_sum($ReturnValueStock)/count($ReturnValueStock);
            $averVN = array_sum($ReturnValueVNIndex)/count($ReturnValueVNIndex);
            
            $ReturnAverageValueStock = array();
            $ReturnAverageValueVNIndex = array();
            for($i =0; $i<count($ReturnValueStock); $i++)
            {
                array_push($ReturnAverageValueStock,$ReturnValueStock[$i]-$averStock);
                array_push($ReturnAverageValueVNIndex,$ReturnValueVNIndex[$i]-$averVN);
            }
            
           if($testMode==1) { echo "<b>Array Return Average: </b>";
                echo "<table><tr><td><h3>Stock</h3></td><td><h3>VN-Index</h3></td></tr><tr><td>";
                var_dump($ReturnAverageValueStock);
                echo "</td><td>";
                var_dump($ReturnAverageValueVNIndex);
                echo "</td></tr></table>";
            } 
            
            $covarTemp = array();
            for($i =0; $i<count($ReturnValueStock); $i++)
            {
                array_push($covarTemp,$ReturnAverageValueStock[$i]*$ReturnAverageValueVNIndex[$i]);               
            }
            
            //var_dump($covarTemp);
            
            
            $Correlation = array_sum($covarTemp)/count($covarTemp);
            echo "Corre: $Correlation";
            echo "<br>Aver Stock: $averStock";
            echo "<br>Aver Index: $averVN";
            $std_index = Stock::model()->standard_deviation($ReturnValueVNIndex,true)*Stock::model()->standard_deviation($ReturnValueVNIndex,true);
            echo "<br>STD^2: $std_index";
            //$std_index = $std_index * $std_index;
            //$stock_index = sqrt(Stock::model()->standard_deviation($ReturnValueStock,true));
            //$Correlation = round(Stock::model()->Correlation($ReturnValueStock,$ReturnValueVNIndex),4);
            $Correlation = $Correlation / $std_index;
            
            $aValue = $averStock - $averVN*$Correlation;
            if($testMode==1) { echo "<b>Correlation(a): </b>";
            echo $Correlation;
            echo "<br><b>Average Stock:</b> $averStock<br><b>Average VNINDEX:</b> $averVN<br><b>b:</b> $aValue<br>"; }
            
            echo "<br><br><h2><b>Result:</b> y = $Correlation * x + $aValue</h2>";
            for($i = 0; $i<count($ReturnValueVNIndex);$i++)
            {
                $ReturnCT = $Correlation * $ReturnValueVNIndex[$i] + $aValue;
                $SSReg = $SSReg + ($ReturnCT- $returnValue)*($ReturnCT - $returnValue);
            }
            $Jensen = 0.12 * (1 - $aValue);
            echo "<br><br><h2><b>Jensen alpha:</b> $Jensen</h2>";
            $valueRSquare = $SSReg/$SSTot;
            echo "<br><br><h2><b>R square = SS reg / SS tot = </b> $SSReg / $SSTot = $valueRSquare</h2>";
           
        }
    }

    public function actionFormulaCal() {
        if (Yii::app()->request->isAjaxRequest)
        {
            $numPort = 300;
            $testMode = 0; 
            session_start();
            $filename = session_id();
            $countAsset = Yii::app()->request->getPost('house');
            $NumPorts = 200;
            $BorrowRate = Yii::app()->request->getPost('BorrowRate');
            $InvestmentHorizon = Yii::app()->request->getPost('depth');
            $ReturnStep = Yii::app()->request->getPost('step');
            //$InvestmentHorizon = 30;
            //$ReturnStep = 1;
            $connection=Yii::app()->db;
            $StockValue = array(); /// Array Gia tri Close Price
            $ReturnValue = array(); /// Array Return value
            $TimeValue0 = array(); // Array Time  = 0
            $TimeValue = array(); /// Array Time != 0
            $StockIDValue = array(); /// Array Stock ID
            $MeanArray = array(); /// Array Mean
            $StdArray = array(); /// Array Std
            $CorrelationArray = array();
        
		
            $ExpReturn2 = "";
            for ($i = 1; $i <= $countAsset; $i++) {
                $ExpReturn2 .= Yii::app()->request->getPost('mean'.$i);
                if ($i != $countAsset)
                    $ExpReturn2 .= " ";
            }
           // echo $countAsset;
            $ExpStd2 = "";
            for ($i = 1; $i <= $countAsset; $i++) {
                $ExpStd2 .= Yii::app()->request->getPost('std'.$i);
                if ($i != $countAsset)
                    $ExpStd2 .= " ";
            } 
            $ExpCovariance2 = "";
            for ($i = 1; $i <= $countAsset; $i++) {
                for($j = 1; $j<=$countAsset; $j++) {
                if($i==$j) $ExpCovariance2 .= 1*Yii::app()->request->getPost('std'.$i)*Yii::app()->request->getPost('std'.$j);
                if($i>$j) $ExpCovariance2 .= Yii::app()->request->getPost('corr'.$i.'-'.$j)*Yii::app()->request->getPost('std'.$i)*Yii::app()->request->getPost('std'.$j);
              else $ExpCovariance2 .= Yii::app()->request->getPost('corr'.$j.'-'.$i)*Yii::app()->request->getPost('std'.$i)*Yii::app()->request->getPost('std'.$j); 
                if ($i != ($countAsset)||$j != ($countAsset))
                    $ExpCovariance2 .= " ";
                    }
            }
            
            /////////////////
            $inputPortror1 = "";
            for($i = 1;$i<=$countAsset;$i++)
            {
                $inputPortror1 .= Yii::app()->request->getPost('iwt'.$i);
                if ($i != $countAsset)
                    $inputPortror1 .= " ";
            }
            ////////////// Goi console portopt

            $command = "/var/www/FIP/protected/matlab/scripts/fip_portopt/run_fip_portopt.sh /opt/MATLAB/MATLAB_Compiler_Runtime/v715/ $countAsset \"$ExpReturn2\" \"$ExpCovariance2\" 300"; 
            if($testMode==1) echo $command;
            $stringExec = shell_exec  ($command);
            //echo $stringExec."<br>".strlen($stringExec);

            
            
            
            ///////////// Goi console portror
            $command = "/var/www/FIP/protected/matlab/scripts/fip_portstats/run_fip_portstats.sh /opt/MATLAB/MATLAB_Compiler_Runtime/v715/ $countAsset \"$ExpReturn2\" \"$ExpCovariance2\" \"$inputPortror1\"";
            if($testMode==1) echo $command;
            $stringExecPortror = shell_exec  ($command);
            if($testMode==1) echo "<br>".$stringExecPortror;            
            //////////////////// Su ly di lieu tra ve cua portror chon ra ket qua phu hop
            $piecesPortror = explode("%%", $stringExecPortror);
            $resultWeight = explode(",", $piecesPortror[1]);
            
            
            
            
         
            if(strlen($stringExec)>300) {
            
                $overNum = 1;
            
                //////////////////// Su ly di lieu tra ve cua portopt chon ra ket qua phu hop
                if($testMode==1) echo "<br><br><br>";
                $pieces = explode("screen.", $stringExec);
                $stringExec = $pieces[1]; // piece1
                if($testMode==1) echo $stringExec;
                $ReturnArrayResult = explode(",", $stringExec);

                $minExp = -100;
                $arrayResultAll = array();
                $roundVel = 2 + $countAsset;
                for($i = 0;$i<300;$i++)
                {
                    $tempArrayResult = array();
                    for($j = 0; $j<$roundVel;$j++)
                    {
                         if(strlen($ReturnArrayResult[$i*$roundVel+$j])>40) $overNum = 2;
                         array_push($tempArrayResult,$ReturnArrayResult[$i*$roundVel+$j]);
                    }
                    if($i==299 && $tempArrayResult[1]<$BorrowRate)
                    {
                        $arrayResultAll = $tempArrayResult;
                        $i=300;
                        $overNum = 0;
                    }
                    if($tempArrayResult[1]>=$BorrowRate) {
                        $arrayResultAll = $tempArrayResult;
                        $i=300;
                    } else {
                        if($testMode==1) { print_r($tempArrayResult);
                        echo "<br>"; }
                    }
                    unset($tempArrayResult);
                }
                              
                
                
                
                if($testMode==1) { echo "<br><Br><br><br>";
                print_r($arrayResultAll); }
                
                /////////////////////////////////
                
                # The data for the pie chart
                $dataChart2 = array();
                $dataChart1 = array();
                $labelsChart = array();
                $dataChart = array();
                for($i = 1;$i<=$countAsset;$i++)
                {
                    array_push($dataChart,Yii::app()->request->getPost('iwt'.$i));
                }
                for($i = 1;$i<=$countAsset;$i++)
                {
                    array_push($labelsChart,Yii::app()->request->getPost('stock_id'.$i));
                }
                
                for($i = 2;$i<count($arrayResultAll);$i++)
                {
                    array_push($dataChart1,$arrayResultAll[$i]);
                }
            
                
                //////////// chart guest
                $c = new PieChart(360, 300);
                $c->setPieSize(180, 140, 100);
                $c->setData($dataChart, $labelsChart);
                $imageCode = $c->makeChart2(PNG);
                $imageCode = base64_encode($imageCode);
                
                
                ////////// chart portopt
                $d = new PieChart(360, 300);
                $d->setPieSize(180, 140, 100);
                $d->setData($dataChart1, $labelsChart);
                $imageCode1 = $d->makeChart2(PNG);
                $imageCode1 = base64_encode($imageCode1);

                if($overNum==2) {
                echo "<h2>Không thể dự đoán trường hợp đầu tư này! Hãy chọn các danh mục khác!</h2>";
                } else {
                if($overNum==0) $textOverNum = "<br>Lợi nhuận của bạn nhập vào quá cao. Đây là kết quả có lợi nhuận cao nhất được tìm thấy!"; else $textOverNum = "";
                echo "<div id=\"stock-grid\" class=\"grid-view\"><table class=\"items\"><tr><td><img src=\"data:image/png;base64,$imageCode\" /><br>Rủi ro: ".$resultWeight[0]."<br>Lợi nhuận: ".$resultWeight[1]."</td>
                        <td><img src=\"data:image/png;base64,$imageCode1\" /><br>Rủi ro: ".$arrayResultAll[0]."<br>Lợi nhuận: ".$arrayResultAll[1]."$textOverNum</td></tr></table></div>";
                }
            } else {
                echo "<h2>Không thể dự đoán vì tương quan giữa các cổ phiếu quá thấp. Hãy chọn cổ phiếu khác!</h2>";
            }
            



         }
    }

}